package com.zjl.spring.第06章_事务;

import com.alibaba.druid.pool.DruidDataSource;
import com.zjl.spring.SpringNApplication;
import com.zjl.spring.第06章_事务.spring.BankService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.math.BigDecimal;

@Configuration//配置类
@ComponentScan(basePackages = "com.zjl.spring.第06章_事务")//组件扫描
@EnableTransactionManagement//开启事务
public class 全注解事务配置 {

    @Bean//创建数据库连接池
    public DruidDataSource getDruidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf8&useSSl=false&serverTimezone=UTC");
//        druidDataSource.setUrl("jdbc:mysql:///spring");  //同上
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        return druidDataSource;//DruidDataSource 实现了 ManagedDataSource 接口  他又实现了 DataSource 接口,所以相当于注入了 DataSource
    }
    @Bean//创建JdbcTemplate对象d
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);//注入数据源  这样不好
//        jdbcTemplate.setDataSource(getDruidDataSource());//注入数据源  这样不好  因为之前创建过了   不需要在创建了
        return jdbcTemplate;
    }
    @Bean //创建事务管理器
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Autowired
    BankService bankService;

    @Test
    public void 全注解(){
        ApplicationContext context = new AnnotationConfigApplicationContext(全注解事务配置.class);
        BankService bankService = context.getBean("bankService", BankService.class);
        System.out.println(bankService.queryAll());
        bankService.accountMoney(new BigDecimal(100.0),false);//false  正常执行   true:模拟异常回滚
        System.out.println(bankService.queryAll());
    }



}
